/*
 * parser.l
 *
 *  Created on: Apr 20, 2011
 *      Author: mariano
 */

%{
#include "../include/element.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char * magic = NULL;;

%}

%option noyywrap

firstElement [A-Za-z0-9!]+[" "\n\t]*
lastElement [A-Za-z0-9!]+[" "\t]*

%%

[" "\t]*{firstElement}+"+"[" "\n\t]*{lastElement}+[\n] {	
	// Just to prevent strcpy from overflowing in case lex does something wrong
	yytext[yyleng] = '\0';

	// yyleng is equivalent to strlen(yytext), that explains the + 1
	magic = malloc(sizeof(char) * (yyleng+1));
	strcpy(magic, yytext);
	return;
}

. { }
[" "\t]\n { }
.\n { return; }

%%

char * parseElement(char * src, int srcSize) {
	int i;
	char * out = malloc(sizeof(char) * srcSize);
	int outSize=0;
	
	// First, transform newlines to spaces
	for(i=0;i<srcSize && src[i] != '\0';i++)
		if(src[i] == '\n' || src[i] == '\t')
			src[i] = ' ';
	
	// Now get rid of duplicated spaces
	for(i=0;i<srcSize && src[i] != '\0';i++)
		if(src[i] != '+' 
		   && (src[i] != ' ' || (i > 0 && src[i] == ' ' && src[i-1] != ' ')))
				out[outSize++] = src[i]; // Replace \n for spaces			
	
	// Erase last possible space
	if(out[outSize-1] == ' ')
		out[outSize-1] = '\0';
	else out[outSize++] = '\0';
	
	// Resize it and return
	out = realloc(out, outSize);
	return out;
}



Magic * parseMagic() {

	if(magic != NULL){
		free(magic);
		magic = NULL;
	}

	parserlex();

	if (magic == NULL)
		return NULL;
	
	int firstSize = 0;
	while (magic[firstSize] != '+' && magic[firstSize++] != '\0');

	char * firstElement = parseElement(magic, firstSize+1);
	char * secondElement = parseElement(magic+firstSize+1,strlen(magic+firstSize+1)+1);

	return newMagic(newElement(firstElement), newElement(secondElement), newElement("Null element."));
}